package com.stormragetech.teamwork.common.util;

import com.stormragetech.common.exception.StormragetechException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
public class SecurityUtils {

    public static String md5(String source) throws StormragetechException {

        StringBuffer hexValue = new StringBuffer();

        try {

            MessageDigest md5 = MessageDigest.getInstance("MD5");

            char[] charArray = source.toCharArray();
            byte[] byteArray = new byte[charArray.length];

            for (int i = 0; i < charArray.length; i++)
                byteArray[i] = (byte) charArray[i];

            byte[] md5Bytes = md5.digest(byteArray);

            for (byte md5Byte : md5Bytes) {
                int val = ((int) md5Byte) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }

        } catch (NoSuchAlgorithmException e) {
            throw new StormragetechException("1002", e.getMessage(), e);
        }

        return hexValue.toString();
    }

    public static String pass(String pass, String salt) throws StormragetechException {

        pass = md5(pass + salt);
        pass = md5(salt + pass);
        return pass;
    }

}
